const { app, BrowserWindow, MessageChannelMain, shell, Menu, dialog, screen } = require('electron');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const log4js = require('log4js');
const task = require('./task');
const common = require('./common');
let childP;
common.initDb();

let logger = log4js.getLogger();
// let diskName = __dirname.split(':')[0] + ':';

function createWindow() {
    // Create the browser window.
    Menu.setApplicationMenu(null);
    const mainWindow = new BrowserWindow({
        width: 1090,
        height: 750,
        maximizable: false,
        resizable: false,
        icon: 'static/logo.ico',
        webPreferences: {
            preload: path.join(__dirname, 'js/preload.js'),
            devTools: true
        }
    });
    mainWindow.loadFile('index.html');
    const { port1, port2 } = new MessageChannelMain();

    // 允许在另一端还没有注册监听器的情况下就通过通道向其发送消息 消息将排队等待，直到有一个监听器注册为止。
    // 我们也可以接收来自渲染器主进程的消息。
    port2.on('message', async event => {
        try {
            let accounts = [];
            switch (event.data.cmd) {
                case 'openPath':
                    var paths = event.data.fullPath.split('\\');
                    paths.pop();
                    shell.openPath(paths.join('\\'));
                    break;
                case 'startTask':
                    task.test();
                    break;
                case 'stopTask':
                    common.closeBrowser();
                    app.quit();
                    break;
                case 'saveConfig':
                    let configs = event.data.configs;

                    for (let i = 0; i < configs.length; i++) {
                        let config = configs[i];
                        common.setConfig(config.key, config.value);
                    }

                    port2.postMessage({ message: '参数已保存' });
                    break;
                case 'accountLogin':
                    await task.accountLogin();
                    break;
                default:
                    break;
            }
        } catch (error) {
            logger.error(error.message + '\r\n' + error.stack);
        }
    });

    common.getConfig('clientName', '终端' + common.randomNum(10, 99));
    common.getConfig('userName', 'manager');
    common.getConfig('code', '618923');
    common.getConfig('requestInterval', '10');
    common.getConfig('exePath', '');
    common.getConfig('proxyApi', '');
    let configs = common.getConfigs();
    port2.postMessage({ cmd: 'initConfigs', configs: configs })
    port2.start();
    mainWindow.webContents.postMessage('main-world-port', null, [port1]);

    if (!app.isPackaged) {
        common.apiUrl = 'http://www.dy.com';
        mainWindow.webContents.openDevTools();
    }

    common.logger.warn(common.apiUrl)
}

app.whenReady().then((callback) => {
    // let primaryDisplay = screen.getPrimaryDisplay();
    // common.scaleFactor = primaryDisplay.scaleFactor;
    // common.screenHeight = primaryDisplay.size.height * primaryDisplay.scaleFactor;
    // common.taskbarHeight = (primaryDisplay.size.height - primaryDisplay.workAreaSize.height) * primaryDisplay.scaleFactor;
    createWindow();
});

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
});


